package dao.impl;

import dao.UserDao;
import domain.User;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import utils.JdbcUtils;

import java.util.List;

public class DaoImpl implements UserDao {
    JdbcTemplate template = JdbcUtils.getJdbcTemplate();

    @Override
    public List<User> findList() {
        String sql = "select * from user";
        List<User> list = template.query(sql, new BeanPropertyRowMapper<>(User.class));
        return list;
    }

    @Override
    public boolean deleteById(String id) {
        String sql = "delete from user where id=?";
        int i = template.update(sql, id);
        return i != 0;
    }

    @Override
    public User findById(String id) {
        String sql = "select * from user where id=?";
        List<User> query = template.query(sql, new BeanPropertyRowMapper<>(User.class), id);
        if (query.size() == 1) {
            User user = query.get(0);
            return user;
        } else {
            return null;
        }
    }

    @Override
    public boolean updateUser(User user) {
        String sql = "update user set name=?,sex=?,age=?,address=?,qq=?,email=? where id=?";
        int i = template.update(sql, user.getName(), user.getSex(), user.getAge(), user.getAddress(), user.getQq(), user.getEmail(), user.getId());
        return i != 0;
    }

    @Override
    public boolean addUser(User user) {
        String sql = "insert into user values (null,?,?,?,?,?,?)";//注意,由于id在数据库中的格式是自增长的,所以,在update方法中不需要写
        int addUser = template.update(
                sql,
                user.getName(),
                user.getSex(),
                user.getAge(),
                user.getAddress(),
                user.getQq(),
                user.getEmail());
        return addUser != 0;
    }

    @Override
    public List<User> queryPage(int offset, int count) {
        String sql ="select * from user limit ?,?";
        List<User> list = template.query(sql, new BeanPropertyRowMapper<>(User.class), offset, count);
        return list;
    }

    @Override
    public int findSum() {
        String sql = "select count(*) from user";
        Integer pageSum = template.queryForObject(sql, int.class);
        return pageSum;
    }
}
